package com.zf.shuashua.helper;

import android.content.Context;
import android.content.Intent;

import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.commonsdk.statistics.common.DeviceConfig;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.PlatformConfig;
import com.zf.shuashua.BuildConfig;
import com.zf.shuashua.MainActivity;
import com.zf.shuashua.ShuaApplication;
import com.zf.shuashua.api.Constants;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.bean.ExtraBean;
import com.zf.shuashua.channel.ChannelUtil;
import com.zf.shuashua.ui.gift.H5Activity;
import com.zf.shuashua.ui.mine.FriendsDetailsActivity;
import com.zf.shuashua.ui.mine.LogUtil;
import com.zf.shuashua.ui.mine.LoginActivity;
import com.zf.shuashua.ui.mine.notice.MessageActivity;

import org.android.agoo.huawei.HuaWeiRegister;
import org.android.agoo.mezu.MeizuRegister;
import org.android.agoo.oppo.OppoRegister;
import org.android.agoo.vivo.VivoRegister;
import org.android.agoo.xiaomi.MiPushRegistar;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;


/**
 * @类作用描述:
 * @作者: lxd小林
 * @创建时间: 2020-02-11 21:18
 * @更新作者:
 * @更新时间: 2020-02-11 21:18
 * @更新说明: 更新说明
 * @版本:
 */
public class UmengHelper {
    private static UmengHelper umengHelper;
    private Context context = ShuaApplication.getContext();

    public static UmengHelper getInstance() {
        if (null == umengHelper) {
            umengHelper = new UmengHelper();
        }
        return umengHelper;
    }

    /**
     * 友盟初始化
     * <p>
     * 友盟初始化及相关配置
     * 注册
     * 通道配置
     */

    public void init() {
        UMConfigure.setLogEnabled(BuildConfig.ENABLE_DEBUG);
//        MobclickAgent.setCatchUncaughtExceptions(!BuildConfig.ENABLE_DEBUG);
        /**
         * 初始化common库
         * 参数1:上下文，必须的参数，不能为空
         * 参数2:友盟 app key，非必须参数，如果Manifest文件中已配置app key，该参数可以传空，则使用Manifest中配置的app key，否则该参数必须传入
         * 参数3:友盟 channel，非必须参数，如果Manifest文件中已配置channel，该参数可以传空，则使用Manifest中配置的channel，否则该参数必须传入，channel命名请详见channel渠道命名规范
         * 参数4:设备类型，必须参数，传参数为UMConfigure.DEVICE_TYPE_PHONE则表示手机；传参数为UMConfigure.DEVICE_TYPE_BOX则表示盒子；默认为手机
         * 参数5:Push推送业务的secret，需要集成Push功能时必须传入Push的secret，否则传空
         * 如果AndroidManifest.xml清单配置中没有设置appkey和channel，则可以在这里设置
         */
//        UMConfigure.preInit(context, Constants.UM_KEY, ChannelUtil.getChannelName(context));
        UMConfigure.init(context, Constants.UM_KEY, ChannelUtil.getChannelName(context), UMConfigure.DEVICE_TYPE_PHONE, Constants.UM_MESSAGE_KEY);
//        UMConfigure.init(context, UMConfigure.DEVICE_TYPE_PHONE, Constants.UM_MESSAGE_KEY);
        //小米
        MiPushRegistar.register(context, "2882303761518287556", "5871828740556");
        //华为
        HuaWeiRegister.register((ShuaApplication) context);
        //OPPO通道，参数1为app key，参数2为app secret
        OppoRegister.register(context, "929e333d5cbc4a6c91315fffb33ff45d", "6900b1dbdfe245008fcc167fc94e9c4b");
        //vivo 通道
        VivoRegister.register(context);
        //魅族 通道
        MeizuRegister.register(context, "137299", "c16e717a130b42fd8e56c6fb28112bd1");


        UMConfigure.setProcessEvent(true);//支持多进程埋点
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);//页面采集
        PlatformConfig.setWeixin(Constants.WX_APP_ID, Constants.WX_KEY);
        PlatformConfig.setQQZone(Constants.QQ_APP_ID, Constants.QQ_KEY);
        PlatformConfig.setSinaWeibo(Constants.WEIBO_APP_ID, Constants.WEIBO_KEY, Constants.REDIRECTURL);
        PushAgent mPushAgent = PushAgent.getInstance(context);
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                LogUtil.d(deviceToken);
//                ClipboardManager mClipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
//                mClipboardManager.setPrimaryClip(ClipData.newPlainText(null, deviceToken));
            }

            @Override
            public void onFailure(String s, String s1) {
//                LogUtil.d(s + s1 + "onFailure");
//                ClipboardManager mClipboardManager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
//                mClipboardManager.setPrimaryClip(ClipData.newPlainText(null, s + "======" + s1));

            }
        });

        //应用数据统计接口
        mPushAgent.onAppStart();
        //最多展示条数
        mPushAgent.setDisplayNotificationNumber(3);
//        mPushAgent.
        //通知或消息接收
//        setMessageHandler();
        //通知点击
        setNotificationClickHandler();
        LogUtil.d(getTestDeviceInfo(context)[0] + "==" + getTestDeviceInfo(context)[1]);

    }

    public static String[] getTestDeviceInfo(Context context) {
        String[] deviceInfo = new String[2];
        try {
            if (context != null) {
                deviceInfo[0] = DeviceConfig.getDeviceIdForGeneral(context);
                deviceInfo[1] = DeviceConfig.getMac(context);
            }
        } catch (Exception e) {
        }
        return deviceInfo;
    }


    /**
     * MessageHandler有很多回调方法，根据自己需要选择
     */
    private void setMessageHandler() {
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            @Override
            public void dealWithCustomMessage(Context context, UMessage uMessage) {
                super.dealWithCustomMessage(context, uMessage);
                LogUtil.d("UmPushHelper" + uMessage.custom);

            }
        };
        PushAgent.getInstance(context).setMessageHandler(messageHandler);
    }

    private void setNotificationClickHandler() {
        /**
         * 自定义行为的回调处理，参考文档：高级功能-通知的展示及提醒-自定义通知打开动作
         * UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * */
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {


            @Override
            public void launchApp(Context context, UMessage msg) {
                super.launchApp(context, msg);
//                ExtraBean extraBean;
//                try {
//                    JSONObject object = new JSONObject(msg.extra);
//                    int type = object.getInt("type");
//                    if (type == 1) {
//                        extraBean = new ExtraBean();
//                        extraBean.setType(type);
//                        extraBean.setOpen_id(object.getInt("open_id"));
//                        EventBus.getDefault().postSticky(extraBean);
//                    } else if (type == 2) {
//                        extraBean = new ExtraBean();
//                        extraBean.setType(type);
//                        extraBean.setUser_id(object.getInt("user_id"));
//                        EventBus.getDefault().postSticky(extraBean);
//                    } else if (type == 3) {
//                        extraBean = new ExtraBean();
//                        extraBean.setType(type);
//                        extraBean.setVideo_id(object.getInt("video_id"));
//                        EventBus.getDefault().postSticky(extraBean);
//                    } else if (type == 4) {
//                        extraBean = new ExtraBean();
//                        extraBean.setType(type);
//                    } else if (type == 5) {
//                        extraBean = new ExtraBean();
//                        extraBean.setType(type);
//                        EventBus.getDefault().postSticky(extraBean);
//                    } else if (type == 6) {
//                        extraBean = new ExtraBean();
//                        extraBean.setType(type);
//                        EventBus.getDefault().postSticky(extraBean);
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                    LogUtil.d(e.getMessage() + "----");
//                }

            }

            @Override
            public void openUrl(Context context, UMessage msg) {
                super.openUrl(context, msg);
            }

            @Override
            public void openActivity(Context context, UMessage msg) {
                super.openActivity(context, msg);
                Intent intent = null;
                ExtraBean extraBean;
                try {
                    JSONObject object = new JSONObject(msg.extra);
                    int type = object.getInt("type");
                    if (type == 1) {
                        extraBean = new ExtraBean();
                        extraBean.setType(type);
                        extraBean.setOpen_id(object.getInt("open_id"));
                        intent = new Intent(context, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("bean", extraBean);
                        context.startActivity(intent);
                    } else if (type == 2) {
                        intent = new Intent(context, FriendsDetailsActivity.class);
                        intent.putExtra("USER_ID", object.getInt("user_id") + "");
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    } else if (type == 3) {
                        extraBean = new ExtraBean();
                        extraBean.setType(type);
                        extraBean.setVideo_id(object.getInt("video_id"));
                        EventBus.getDefault().postSticky(extraBean);
                    } else if (type == 4) {
                        if (!Store.getInstance().isLogin()) {
                            intent = new Intent(context, LoginActivity.class);
                        } else {
                            intent = new Intent(context, H5Activity.class);
                            intent.putExtra("money", Constants.H5_URL + "withdraw");
                            intent.putExtra("title", "我的钱包");
                        }
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    } else if (type == 5) {
                        if (!Store.getInstance().isLogin()) {
                            intent = new Intent(context, LoginActivity.class);
                        } else {
                            intent = new Intent(context, MessageActivity.class);
                        }
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent);
                    }
//                    else if (type == 6) {
//                        if (!Store.getInstance().isLogin()) {
//                            intent = new Intent(context, LoginActivity.class);
//                        } else {
//                            intent = new Intent(context, H5Activity.class);
//                            intent.putExtra("money", Constants.H5_URL + "activity_dwj");
//                            intent.putExtra("title", "端午活动");
//                        }
//                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        context.startActivity(intent);
//                    }
                    else if (type == 7) {
                        extraBean = new ExtraBean();
                        extraBean.setType(type);
                        EventBus.getDefault().postSticky(extraBean);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    LogUtil.d(e.getMessage() + "----");
                }
            }

            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
            }
        };
        //使用自定义的NotificationHandler
        PushAgent.getInstance(context).setNotificationClickHandler(notificationClickHandler);

    }

}
